// 此文件用于登录注册
import {reqgetcode,reqRegister,reqLogin,reqUserInfo,reqLogout} from "@/api"
import {getToken,setToken,removeToken} from "@/utils/token"
// 全部商品分类
const state={
    code:"",//验证码
    token:getToken(),//用户token
    usetInfo:{},//用户信息
}
const mutations ={
    GETCODE(state,code){
        state.code=code
    },
    GETUSERINFO(state,usetInfo){
        state.usetInfo=usetInfo
    },
    USERLOGIN(state,token){
        state.token=token
    },
    CLEAR(state){
        state.token="",
        state.usetInfo={},
        // 清除本地数据
        removeToken()
    }
    
}
const actions ={
// test 获取验证码
   async getUserCode({commit},phone){
       let result = await reqgetcode(phone)
       if(result.code==200){
            commit("GETCODE",result.data)
       }
   },
   // 用户注册
   async userRegister({commit},data){
        let result =await reqRegister(data)
        
        if(result.code==200){
            return "ok"
        }else{
            return Promise.reject(new Error("fail"))
        }
    },
    // 用户登录
    async userLogin({commit},user){
        let result =await reqLogin(user)
        if(result.code==200){
            commit("GETUSERINFO",result.data)
            // 用户登录成功获取用户token
            commit("USERLOGIN",result.data.token)
            // 持久化存储token
            setToken(result.data.token)
            
            return "ok"
        }else{
            return Promise.reject(new Error("fail"))
        }

    },
    // 获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo()
        if(result.code==200){
            commit("GETUSERINFO",result.data)
            return "ok"
        }else{
            return Promise.reject(new Error("fail"))
        }
    },
    // 退出登录
    async quitLogin({commit}){
        // 如果用户退出登录,通知服务器退出登录,清除登录信息(token)
        let result = await reqLogout()
        if(result.code===200){
            // 清除项目中的数据(userInfo,token)
            commit("CLEAR")
        }else{
            return Promise.reject(new Error("fail"))
        }
    }
}

const getters={}
export default{
    state,
    mutations,
    actions,
    getters
}